using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace SerialPortCommunicationProject.Tools
{
    /// <summary>
    /// class for socket tcp client communication
    /// parent class: SocketTcpCommunication
    /// </summary>
    public class SocketTcpClientCommunication : SocketTcpCommunication
    {
        private string remoteIp;
        private int remotePort;

        public SocketTcpClientCommunication(int sendBufferSize, int receiveBufferSize, string remoteIp, int remotePort) : base(sendBufferSize, receiveBufferSize)
        {
            this.remoteIp = remoteIp;
            this.remotePort = remotePort;
        }

        public SocketTcpClientCommunication(string remoteIp, int remotePort) : base()
        {
            this.remoteIp = remoteIp;
            this.remotePort = remotePort;
        }

        public override bool Open()
        {
            if (socket == null)
            {
                return false;
            }
            if (!IsOpen)
            {
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(remoteIp), remotePort);
                try
                {
                    socket.Connect(remoteEP);
                    Task.Factory.StartNew(DataReceive);
                }
                catch (Exception ex)
                {
                    return false;
                }
                IsOpen = true;
            }
            return true;
        }

        public override void Send(byte[] sendBuffer)
        {
            socket.Send(sendBuffer, sendBuffer.Length, SocketFlags.None);
            this.sendBuffer = sendBuffer;
            ViewModelHelper.GenerateDataRecord(this, Status.Send);
        }

        public override void DataReceive()
        {
            while (true)
            {
                try
                {
                    int bufferSize = 100;
                    byte[] buffer = new byte[bufferSize];
                    int receivedSize = socket.Receive(buffer, bufferSize, SocketFlags.None);
                    receiveBuffer = buffer.Take(receivedSize).ToArray();
                }
                catch (Exception ex)
                {
                    socket.Close();
                    return;
                }

                ViewModelHelper.GenerateDataRecord(this, Status.Receive);
            }
        }
    }
}
